<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js"></script>
		<style>
			.item {
				width: 200px;
				height: 100px;
				border: #CCCCCC dashed 1px;
				margin-top: 20px;
			}

			.item div {
				height: 35px;
				line-height: 35px;
			}
		</style>
	</head>
	<body>
		<div id="container">
			商品列表：<br>
			<template v-for="g in goodslist">
				<!--在子组件上监听事件 事件名称自己定义 的..-->
				<!-- 此时@close方法中含有商品名称，于是父组件定义cls方法进行接收，并且根据传递的商品名称去goodslist中(根据名字找)执行删除该商品 -->
				<goods :goods="g" @close="cls"></goods>
			</template>
		</div>

		<script>
			var goods = {
				props: {
					goods: {
						type: Object,
						default: function() {
							return {
								name: "无",
								price: 0
							}
						}
					}
				},
				methods: {
					// 当点击按钮时，会触发当前close方法，将并且将商品名字抛给父组件
					close() {
						console.log("子组件执行关闭...")
						//触发该组件的close事件 将当前商品名称抛给父组件  this.goods.name的值用$event接收
						this.$emit("close", this.goods.name);
					}
				},
				template: `
            <div class="item">
                <div>商品名称:{{goods.name}}</div>
                <div>
                    价格:￥<span style="color: #FF0000;">{{goods.price}}</span>
                </div>
				<!-- 给按钮添加点击事件，事件名成称为close -->
                <input type="button" value="关闭" @click="close"/>
            </div>
            `
			};

			new Vue({
				el: "#container",
				data: {
					goodslist: [{
							name: "华为手机",
							price: 2999
						},
						{
							name: "小米手机",
							price: 999
						}
					]
				},
				components: {
					goods
				},
				methods: {
					cls($event) {
						console.log("父组件监听到子组件事件", $event)
						for (var i = 0; i < this.goodslist.length; i++) {
							var tmp = this.goodslist[i];
							//判断遍历到的商品是否是要关闭的商品$event
							if (tmp.name == $event) {
								// 直接移除该商品
								this.goodslist.splice(i, 1);
								break; //终止循环
							}
						}
					}
				}

			});
		</script>
	</body>
</html>
